< previous page page_331 next page >

Page 331
After call ByRef: 6
When a parameter is passed by reference, the called function receives a reference to the variable itself, so any changes made to the parameter are reflected in the value of the original variable.
But what does "a reference to the variable itself" actually mean? It means that the called function is somehow able to modify the contents of the original parameter. But how does it do this?
An in-depth look at how functions are called can be found in Tutorial 4, "How DLL Calls Work: Inside a Stack Frame." This tutorial explains how every parameter that is passed to a function is placed in a separate block of memory, called a stack. Understanding how the ByVal keyword affects the way in which a parameter is placed in the stack is key to understanding when this keyword should be used.
How ByVal Works
Numeric Variables
Every variable has two characteristics. It has a valuethe data "contained" in the variable. And it has a locationthe location in memory where the data is kept.
Figure T5-1 illustrates how a Long variable is passed ByVal to a function.
0331-01.gif
Figure T5-1:
Passing a numeric variable by value
In this example, the value of the variable is 5. It is located at address &H1005654 in memory. Because ByVal was specified, the value of the variable is placed on the stack as a parameter named x. When you refer to x in the CalledByVal function, you are actually referring to the value on the stack, so any changes made to the value can't affect the original variable myvar.
Figure T5-2 illustrates how a Long variable is passed ByRef to a function.

 
< previous page page_331 next page >